package com.fancy.mobileschool.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fancy.mobileschool.MyConfiguration;
import com.fancy.mobileschool.R;
import com.fancy.mobileschool.entity.Attendance;
import com.fancy.mobileschool.entity.Course;
import com.fancy.mobileschool.service.AttendService;
import com.fancy.mobileschool.service.CourseService;
import com.fancy.mobileschool.task.TaskExecutor;
import com.fancy.mobileschool.ui.AttendResultActivity;
import com.fancy.mobileschool.ui.widget.CourseSelectDialog;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Jackie on 2017/11/21.
 *
 */

public class TeacherAttendFragment extends Fragment implements View.OnClickListener{

    private List<Course> courses;

    private CourseService courseService;

    private AttendService attendService;

    private LinearLayout linearLayout;

    private ViewGroup container;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        courseService = new CourseService();
        attendService = new AttendService();
        TaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                courses = courseService.getMyGroupsForTeacher(MyConfiguration.myID);
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.container = container;
        View view = inflater.inflate(R.layout.fragment_teacher_attend, container, false);
        linearLayout = (LinearLayout) view.findViewById(R.id.attendance);
        FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
        fab.setOnClickListener(this);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        updateAttendances();
    }

    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.fab) {
            if (courses == null || courses.size() == 0)
                Toast.makeText(getActivity().getApplicationContext(), "正在加载数据或者你没有添加课程", Toast.LENGTH_SHORT).show();
            else {
                CourseSelectDialog courseSelectDialog = new CourseSelectDialog(getActivity(), courses, new MyCourseSelectListener()
                        , false);
                courseSelectDialog.show();
            }
        }else if (view.getId() == R.id.message_item) {
            Log.i("wode", "click " +  view.getTag());
            SimpleDateFormat day = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();

            String dayStr = day.format(date);
            Intent i = new Intent(getActivity(), AttendResultActivity.class);
            i.putExtra("courseID", (String) view.getTag());
            i.putExtra("day", dayStr);

            getActivity().startActivity(i);

        }


    }

    private class MyCourseSelectListener implements CourseSelectDialog.CourseSelectedListener{

        @Override
        public void courseSelect(String courseTag) {
            Date date = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            SimpleDateFormat day = new SimpleDateFormat("yyyy-MM-dd");


            Attendance attendance = new Attendance();
            attendance.course_id = courseTag;
            attendance.start_time = df.format(date);
            attendance.end_time = df.format(date);
            attendance.day = day.format(date);

            ReleaseAttendanceTask task = new ReleaseAttendanceTask();
            task.execute(attendance);

        }
    }

    private void bindAttendance(Attendance attendance) {
        View studentAttendance = LayoutInflater.from(getActivity())
                .inflate(R.layout.fragment_message_item, container, false);

        TextView textView = (TextView) studentAttendance.findViewById(R.id.message_text);
        textView.setText(attendance.course_name);
        textView.setTextColor(Color.BLACK);

        studentAttendance.setTag(attendance.course_id);
        studentAttendance.setOnClickListener(TeacherAttendFragment.this);

        linearLayout.addView(studentAttendance);
    }

    private void updateAttendances() {
        GetAttendancesTask task = new GetAttendancesTask();
        task.execute();
    }


    private class ReleaseAttendanceTask extends AsyncTask<Attendance, Void, Attendance> {

        @Override
        protected Attendance doInBackground(Attendance... params) {
            return attendService.releaseAttendance(params);
        }

        @Override
        protected void onPostExecute(Attendance attendance) {

            if (attendance != null) {
                View studentAttendance = LayoutInflater.from(getActivity())
                        .inflate(R.layout.fragment_message_item, container, false);
                studentAttendance.setOnClickListener(TeacherAttendFragment.this);

                String courseName = null;
                for (int i = 0; i < courses.size(); i++) {
                    if (attendance.course_id.equals(courses.get(i).course_id))
                        courseName = courses.get(i).name;
                }

                TextView textView = (TextView) studentAttendance.findViewById(R.id.message_text);
                textView.setText(courseName);
                textView.setTextColor(Color.BLACK);

                studentAttendance.setTag(attendance.course_id);
                studentAttendance.setOnClickListener(TeacherAttendFragment.this);

                linearLayout.addView(studentAttendance);

            }
        }
    }

    private class GetAttendancesTask extends AsyncTask<Void, Void, List<Attendance>> {


        @Override
        protected List<Attendance> doInBackground(Void... params) {
            return attendService.getAttendancesForTeacher(MyConfiguration.myID);
        }

        @Override
        protected void onPostExecute(List<Attendance> attendances) {
            super.onPostExecute(attendances);
            linearLayout.removeAllViews();

            if (attendances != null) {
                int size = attendances.size();
                for (int i = 0; i < size ; i++) {
                   bindAttendance(attendances.get(i));
                }
            }
        }
    }
}
